package com.slf.engine.services.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.log4j.Priority;
import com.slf.engine.bo.Order;
import com.slf.engine.common.SysContants;
import com.slf.engine.exception.EngineException;
import com.slf.engine.http.HttpClientManager;
import com.slf.engine.http.HttpResponseWrapper;
import com.slf.engine.services.IBossService;
import com.slf.engine.utils.DateUtils;
import com.slf.engine.utils.KeyedDigestMD5;

public class BossServiceImpl implements IBossService {

	private static final Logger log = Logger.getLogger(BossServiceImpl.class);
	public static final int CLBZ_SUCCESS = 1;
	public static final int CLBZ_ERROR = 2;
	
//	public static final String GET_URL = "http://dingxin.ftp123.com:11140/get_jkextend.do";
//	public static final String BACK_URL = "http://dingxin.ftp123.com:11140/deal_jkextend.do";
	
	private static final String CHARSET = "utf-8";
	/**
	 * @return 订单数组
	 */
	public Order getOneOrder()
	{
		String body = "";
		try {
			StringBuffer url = new StringBuffer(SysContants.DX_GET_URL);
			url.append("?supid=" + SysContants.DX_SUPID);
			url.append("&pwd=" + SysContants.DX_PWD);
			url.append("&supkey=" + KeyedDigestMD5.getKeyedDigest("supid" + SysContants.DX_SUPID + "pwd" + SysContants.DX_PWD + SysContants.DX_KEY, ""));
			HttpResponseWrapper wrapper = new HttpClientManager().execute("GET", url.toString(), CHARSET, null, null, null, null, null);
			if(wrapper.getBody() == null)
			{
				return null;
			}
			
			body = new String(wrapper.getBody(),CHARSET);
//			log.log(Priority.INFO, "获取订单:" + body);
			String ss[] = body.split("\\|");
			if(ss.length > 1)
			{
				Order order = new Order();
				order.setOrderId(ss[1]);
				order.setAccount(ss[2]);
				order.setMoney(ss[3]);
				order.setStarttime(DateUtils.strDate("yyyyMMddHHmmss"));
				return order;
			}
//			if(body.indexOf("xml") == -1)
//			{
//				return null;
//			}
//			HtmlCleaner cleaner = new HtmlCleaner();
//			TagNode bodyNode = cleaner.clean(body);
//			
//			Object orders[] = bodyNode.evaluateXPath("//response/orders");
//			if(orders != null && orders.length > 0)
//			{
//				list = new ArrayList<Order>();
//				for(int i = 0; i < orders.length; i++)
//				{
//					TagNode node = (TagNode)orders[i];
//					Order order = new Order();
//					order.setOrderId(((StringBuffer)node.evaluateXPath("//order/orderid/text()")[0]).toString());
//					order.setAccount(((StringBuffer)node.evaluateXPath("//order/account/text()")[0]).toString());
//					order.setMoney(((StringBuffer)node.evaluateXPath("//order/money/text()")[0]).toString());
//					order.setStarttime(((StringBuffer)node.evaluateXPath("//order/starttime/text()")[0]).toString());
//					list.add(order);
//				}
//			}
			
		} catch (EngineException e) {
			// TODO Auto-generated catch block
			log.log(Priority.ERROR, "无法连接鼎信服务端---3秒后重连");
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
			}
			return getOneOrder();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
		}
		return null;
	}
	
	public boolean doPost(Order order)
	{
		StringBuffer url = new StringBuffer(SysContants.DX_POST_URL);
		url.append("?supid=" + SysContants.DX_SUPID);
		url.append("&pwd=" + SysContants.DX_PWD);
		url.append("&orderid=" + order.getOrderId());
		url.append("&tag=" + SysContants.CZ_RUN);
		url.append("&supkey=" + KeyedDigestMD5.getKeyedDigest("supid" + SysContants.DX_SUPID + "pwd" + SysContants.DX_PWD +
				"orderid" + order.getOrderId() + "tag" + SysContants.CZ_RUN + SysContants.DX_KEY, ""));
		try {
			url.append("&remark=" + URLEncoder.encode("进行中",CHARSET));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
		}
		try {
			log.log(Priority.INFO, "提取返回orderId:" + order.getOrderId() + " account:" + order.getAccount() 
					+ " money:" + order.getMoney());
			HttpResponseWrapper wrapper = new HttpClientManager().execute("GET", url.toString(), CHARSET, null, null, null, null, null);
			if(wrapper.getBody() == null)
			{
				log.log(Priority.INFO,"交易反馈异常，2秒后重新返回");
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
				}
				return doPost(order);
			}
			String body = new String(wrapper.getBody(),CHARSET);
			log.log(Priority.INFO, "交易反馈orderId:" + order.getOrderId() + " info:" + body);
			if(body.indexOf("1") != -1)
			{
				return true;
			}else{
				return false;
			}
		} catch (EngineException e) {
			// TODO Auto-generated catch block
			log.log(Priority.ERROR,"交易返回异常");
			return doPost(order);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
		} 
		return false;
	}
	
	public boolean doBack(Order order)
	{
		StringBuffer url = new StringBuffer(SysContants.DX_BACK_URL);
		url.append("?supid=" + SysContants.DX_SUPID);
		url.append("&pwd=" + SysContants.DX_PWD);
		url.append("&orderid=" + order.getOrderId());
		url.append("&tag=" + order.getClbz());
		url.append("&supkey=" + KeyedDigestMD5.getKeyedDigest("supid" + SysContants.DX_SUPID + "pwd" + SysContants.DX_PWD +
				"orderid" + order.getOrderId() + "tag" + order.getClbz() + SysContants.DX_KEY, ""));
		try {
			url.append("&remark=" + URLEncoder.encode(order.getCljg(),CHARSET));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
		}
		try {
			log.log(Priority.INFO, "交易返回orderId:" + order.getOrderId() + " account:" + order.getAccount() 
					+ " money:" + order.getMoney() + " clbz:" + order.getClbz() + " cljg:" + order.getCljg());
			HttpResponseWrapper wrapper = new HttpClientManager().execute("GET", url.toString(), CHARSET, null, null, null, null, null);
			if(wrapper.getBody() == null)
			{
				log.log(Priority.INFO,"交易反馈异常，2秒后重新返回");
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
				}
				return doBack(order);
			}
			String body = new String(wrapper.getBody(),CHARSET);
			log.log(Priority.INFO, "交易反馈orderId:" + order.getOrderId() + " info:" + body);
			if(body.indexOf("1") != -1)
			{
				return true;
			}else{
				return false;
			}
		} catch (EngineException e) {
			// TODO Auto-generated catch block
			log.log(Priority.ERROR,"交易返回异常");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
		} 
		return false;
	}
	
	
}
